import traceback

from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.utils.deprecation import MiddlewareMixin
from rest_framework import status

from tools.Token import isTokenExpired
from django.db.models import Q
from tools.Tools import res, token_username
from Model.models import User, Role, Operation

FILTER_PATH = ['/api/user/login', '/api/system/oneUser', '/api/system/operation', '/api/system/page',
               '/api/system/pageImg', '/api/business/download/example', '/api/system/getExcelData',
               '/api/business/client/example']


class TokenChecker(MiddlewareMixin):
    """
    检查是否token有效的中间件
    """

    @staticmethod
    def process_request(request):

        res.clear()
        try:
            url_path = request.path
            if url_path in FILTER_PATH:
                return
            else:
                token = request.META.get('HTTP_AUTHORIZATION')
                if isTokenExpired(token):
                    res['status'] = 401
                    res['msg'] = '当前token已过期,请重新登录！'
                    return JsonResponse(res, status=status.HTTP_401_UNAUTHORIZED)
                else:
                    return
        except Exception as e:
            res['status'] = 400
            res['msg'] = '请求错误！'
            return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)


class ApiAuthorityChecker(MiddlewareMixin):
    """
    检查用户对api是否有访问权限的中间件
    """

    @staticmethod
    def process_request(request):
        res.clear()
        try:
            url_path = request.path
            if url_path in FILTER_PATH:
                return
            else:
                token = request.META.get('HTTP_AUTHORIZATION')
                # 校验用户权限
                name = token_username[token]
                if name == 'superAdmin':
                    return
                else:
                    if name.find("@") == -1:
                        userInfo = User.objects.get(telephone=name)
                    else:
                        userInfo = User.objects.get(email=name)
                    roles = userInfo.role
                    operations = []
                    for i in roles.split(","):
                        role = Role.objects.get(role_id=i)
                        operations += role.operation_auth.split(',')
                    operations = list(set(operations))
                    path_list = []
                    for i in operations:
                        op = Operation.objects.get(operation_id=i)
                        path_list.append(op.path)
                    path_list = list(set(path_list))
                    if url_path in path_list:
                        return
                    else:
                        # 没有权限
                        res['status'] = 403
                        res['message'] = '无访问权限！'
                        return JsonResponse(res, status=status.HTTP_403_FORBIDDEN)
        except Exception as e:
            print(e)
            res['status'] = 400
            res['message'] = '请求错误！'
            return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)
